﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ProgramUpDate
{    
    public class FtpHelp
    {
        #region FTPConfig
        string ftpURI { get; }
        string ftpUserID { get; }
        string ftpServerIP { get; }
        string ftpPassword { get; }
        string ftpRemotePath { get; }
        #endregion

        /// <summary>  
        /// 连接FTP服务器
        /// </summary>  
        /// <param name="FtpServerIP">FTP连接地址</param>  
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
        /// <param name="FtpUserID">用户名</param>  
        /// <param name="FtpPassword">密码</param>  
        public FtpHelp(string FtpServerIP, string FtpUserID, string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = "";// FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI = "ftp://" + ftpServerIP + "/";
        }


        /// <summary>
        /// 判断FTP连接
        /// </summary>
        /// <returns></returns>
        public bool CheckFtp()
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                // ftp用户名和密码
                ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Timeout = 3000;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();

                ftpResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="localfile">参数localfile为要上传的本地文件</param>
        /// <param name="ftpfile">ftpfile为上传到FTP的文件名称</param>
        /// <param name="pb"></param>
        public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
        {
            FileInfo fileInf = new FileInfo(localfile);
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            if (pb != null)
            {
                pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
                pb.Maximum = pb.Maximum + 1;
                pb.Minimum = 0;
                pb.Value = 0;
            }
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    if (pb != null)
                    {
                        if (pb.Value != pb.Maximum)
                            pb.Value = pb.Value + 1;
                    }
                    contentLen = fs.Read(buff, 0, buffLength);
                    System.Windows.Forms.Application.DoEvents();
                }
                if (pb != null)
                    pb.Value = pb.Maximum;
                System.Windows.Forms.Application.DoEvents();
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="localfilename">参数localfilename为将下载到本地的文件名称</param>
        /// <param name="ftpfileName">ftpfilename为要下载的FTP上文件名称</param>
        /// <param name="pb"></param>
        public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
        {
            Common.WriterLogs("FtpHelp.Download【文件下载】",string.Format("localfilename:{0}  ftpfileName:{1} ", localfilename, ftpfileName));
            try
            {
                long fileSize = GetFileSize(ftpfileName);
                if (fileSize > 0)
                {
                    if (pb != null)
                    {
                        pb.Maximum = Convert.ToInt32(fileSize / 2048);
                        pb.Maximum = pb.Maximum + 1;
                        pb.Minimum = 0;
                        pb.Value = 0;
                    }
                    try
                    {
                        string[] directorys = localfilename.Split('\\');
                        string directory = string.Empty;
                        for (int i = 0; i < directorys.Count() - 1; i++)
                        {
                            directory += directorys[i] + "\\";
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                        }
                        //判断是否只读，修改只读属性
                        if(File.Exists(localfilename))
                            System.IO.File.SetAttributes(localfilename, FileAttributes.Normal);                        
                        FileStream outputStream = new FileStream(localfilename, FileMode.Create);
                        FtpWebRequest reqFTP;
                        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
                        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                        reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                        reqFTP.UseBinary = true;
                        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                        Stream ftpStream = response.GetResponseStream();
                        int bufferSize = 2048;

                        int readCount;
                        byte[] buffer = new byte[bufferSize];
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            if (pb != null)
                            {
                                if (pb.Value != pb.Maximum)
                                    pb.Value = pb.Value + 1;
                            }
                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                            System.Windows.Forms.Application.DoEvents();
                        }
                        if (pb != null)
                            pb.Value = pb.Maximum;
                        System.Windows.Forms.Application.DoEvents();
                        ftpStream.Close();
                        outputStream.Close();
                        response.Close();
                    }
                    catch (Exception ex)
                    {
                        File.Delete(localfilename);
                        throw new Exception(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="dirName"></param>
        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 获取指定FTP文件大小
        /// </summary>
        /// <param name="ftpfileName"></param>
        /// <returns></returns>
        public long GetFileSize(string ftpfileName)
        {
            long fileSize = 0;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return fileSize;
        }

        /// <summary>
        /// 获取当前目录下文件夹
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDirList(string ftpfileName)
        {

            // string[] downloadFiles;
            try
            {
                StringBuilder result = new StringBuilder();//如果要修改字符串而不创建新的对象，则可以使用 System.Text.StringBuilder 类。
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));//"ftp://10.12.12.9";
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//目录
                WebResponse response = ftp.GetResponse();//response为一个ftp的WebResponse
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);//读入responses所创建的数据流
                string line = reader.ReadLine();//输入流中的下一行；如果到达了输入流的末尾，则为空引用
                while (line != null)
                {
                    result.Append(line);//)Append 方法可用来将文本或对象的字符串表示形式添加到由当前 StringBuilder 对象表示的字符串的结尾处。
                    result.Append("\n");
                    line = reader.ReadLine();
                    //textBox1.Text = line;
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);//移除最后的换行》？
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //===================================================
        /// <summary>
        /// 获取选中文件夹下的文件
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesList(string ftpfileName)//
        {
            //string url = path + "/" + SelectDir;//============和之前的文件夹唯一的不同就在于此，加上了文件夹的名字..我会优化的
            try
            {
                StringBuilder result = new StringBuilder();//如果要修改字符串而不创建新的对象，则可以使用 System.Text.StringBuilder 类。
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//目录
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//读入responses所创建的数据流
                string pattern = @"^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$";
                Regex regex = new Regex(pattern);
                IFormatProvider culture = CultureInfo.GetCultureInfo("en-us");
                string line = reader.ReadLine();//输入流中的下一行；如果到达了输入流的末尾，则为空引用
                if (line == null)
                {
                    string[] strs = { };
                    return strs;
                }
                while (line != null)
                {
                    Match match = regex.Match(line);
                    string s = match.Groups[1].Value;
                    DateTime modified =
                        DateTime.ParseExact(s, "MM-dd-yy  hh:mmtt", culture, DateTimeStyles.None);
                    string type = match.Groups[2].Value;
                    string name = match.Groups[3].Value;

                    result.Append(name + "|" + type + "|" + modified.ToString("yyyy-MM-dd HH:mm"));
                    result.Append("\n");
                    line = reader.ReadLine();
                    //textBox1.Text = line;
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);//移除最后的换行》？
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');                
            }
            catch (Exception ex)
            {
                throw ex;
            }            
        }

        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = ftpURI + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错：" + ex.Message);
            }
            return strs;
        }

        /// <summary>
        /// 判断ftp上是否存在指定文件夹
        /// </summary>
        /// <param name="directory"></param>
        /// <returns></returns>
        public bool DirectoryExists(string directory)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + directory));
                request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII))
                {
                    sr.ReadToEnd();
                }
                return true;
            }
            catch { }
            return false;
        }
    }
}
